<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="500px"
    append-to-body
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="选手" prop="playerId">
        <el-select
          v-model="form.playerId"
          placeholder="请选择选手"
          style="width: 100%"
          :disabled="form.id !== undefined"
        >
          <el-option
            v-for="item in playerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="介绍视频" prop="videoName">
        <el-upload
          class="upload-video"
          action="#"
          :http-request="uploadVideo"
          :show-file-list="false"
          :before-upload="beforeVideoUpload"
        >
          <video
            v-if="form.videoName"
            :src="videoUrl"
            class="video-preview"
            controls
          ></video>
          <el-button v-else type="primary">点击上传视频</el-button>
          <div slot="tip" class="el-upload__tip">只能上传mp4文件</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listPlayer, addPlayerIntroduce } from "@/api/player";
import { put, getFileNameUUID, getFileName, getFile } from "@/utils/ali-oss";

export default {
  name: "EditIntroduce",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      form: {
        id: undefined,
        playerId: undefined,
        playerName: undefined,
        videoName: "",
      },
      videoUrl: "",
      rules: {
        playerId: [
          { required: true, message: "请选择选手", trigger: "change" },
        ],
        videoName: [
          { required: true, message: "请上传介绍视频", trigger: "change" },
        ],
      },
      playerOptions: [],
    };
  },
  created() {
    this.getPlayerOptions();
  },
  watch: {
    "form.videoName": {
      immediate: true,
      async handler(newVal) {
        if (newVal) {
          this.videoUrl = await getFile(newVal);
        } else {
          this.videoUrl = "";
        }
      },
    },
    "form.playerId": {
      handler(newVal) {
        if (newVal) {
          const selectedPlayer = this.playerOptions.find(
            (item) => item.value === newVal
          );
          this.form.playerName = selectedPlayer ? selectedPlayer.label : "";
        } else {
          this.form.playerName = "";
        }
      },
    },
  },
  methods: {
    getPlayerOptions() {
      listPlayer()
        .then((response) => {
          this.playerOptions = response.rows.map((item) => ({
            label: item.name,
            value: item.id,
          }));
        })
        .catch((error) => {
          this.$message.error("获取选手列表失败");
          console.error("获取选手列表失败", error);
        });
    },
    reset() {
      this.form = {
        id: undefined,
        playerId: undefined,
        playerName: undefined,
        videoName: "",
      };
      this.resetForm("form");
    },
    cancel() {
      this.reset();
      this.$emit("update:visible", false);
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            content: this.form.videoName,
            playerId: this.form.playerId,
            playerName: this.form.playerName,
          };

          addPlayerIntroduce(params)
            .then((res) => {
              this.$modal.msgSuccess("保存成功");
              this.$emit("success");
              this.cancel();
            })
            .catch((error) => {
              this.$message.error("保存失败：" + (error.message || "未知错误"));
            });
        }
      });
    },
    beforeVideoUpload(file) {
      const isMP4 = file.type === "video/mp4";
      if (!isMP4) {
        this.$message.error("只能上传 mp4 格式的视频！");
        return false;
      }
      return true;
    },
    async uploadVideo(params) {
      const formData = new FormData();
      formData.append("file", params.file);

      try {
        const fileName = getFileNameUUID() + getFileName(params.file.name);
        const result = await put(fileName, params.file);
        if (result) {
          this.form.videoName = fileName;
          this.$message.success("视频上传成功");
        } else {
          throw new Error("上传返回结果格式错误");
        }
      } catch (error) {
        console.error("视频上传失败", error);
        this.$message.error("视频上传失败：" + (error.message || "未知错误"));
      }
    },
    setFormData(data) {
      this.form = { ...data };
    },
  },
};
</script>

<style scoped>
.video-preview {
  width: 100%;
  height: 200px;
  object-fit: cover;
}
.upload-video {
  width: 100%;
}
.dialog-footer {
  text-align: right;
}
</style>
